package com.boot.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.boot.dto.AssignRoleDTO;
import com.boot.entity.Result;
import com.boot.entity.SysUserRole;
import com.boot.service.ISysUserRoleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys-user-role")
public class SysUserRoleController {

    @Resource
    private ISysUserRoleService userRoleService;

    /**
     * 获取用户已绑定的角色 ID 列表
     */
    @GetMapping("/user/{userId}")
    public Result<List<Long>> getRolesByUser(@PathVariable Long userId) {
        List<Long> roleIds = userRoleService.list(
                        Wrappers.<SysUserRole>lambdaQuery()
                                .eq(SysUserRole::getUserId, userId))
                .stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
        return Result.success(roleIds);
    }

    /**
     * 给用户分配角色（覆盖式）
     */
    @PostMapping("/assign")
    public Result<String> assignRoles(@Valid @RequestBody AssignRoleDTO dto) {
        Long userId = dto.getUserId();
        List<Long> roleIds = dto.getRoleIds();

        userRoleService.remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));

        if (roleIds.isEmpty()) {
            return Result.success("角色已清空");
        }

        List<SysUserRole> list = roleIds.stream().map(roleId -> {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            return ur;
        }).collect(Collectors.toList());

        if (userRoleService.saveBatch(list)) {
            return Result.success("分配角色成功");
        }
        return Result.fail("分配失败");
    }

    /**
     * 批量获取多个用户的当前角色映射（可用于表格显示）
     */
    @GetMapping("/list-by-users")
    public Result<List<SysUserRole>> listByUsers(@RequestParam List<Long> userIds) {
        List<SysUserRole> relations = userRoleService.list(
                Wrappers.<SysUserRole>lambdaQuery()
                        .in(SysUserRole::getUserId, userIds)
        );
        return Result.success(relations);
    }
}
